#   LibAut
#       Figure 4 
#   Matthew Wilson
#   Juraj Medzihorsky
#   2021-14-09

library(gridExtra)
library(dplyr)
library(ggplot2)
library(ggpubr)
library(ggthemes)

#   #   sessionInfo()
#   R version 3.6.3 (2020-02-29)
#   Platform: x86_64-pc-linux-gnu (64-bit)
#   Running under: Ubuntu 16.04.7 LTS

#   Matrix products: default
#   BLAS/LAPACK: /opt/OpenBLAS/lib/libopenblas_haswellp-r0.3.9.so

#   locale:
#    [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
#    [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_GB.UTF-8       LC_NAME=C
#    [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

#   attached base packages:
#   [1] stats     graphics  grDevices utils     datasets  methods   base

#   other attached packages:
#   [1] ggthemes_4.1.1 ggpubr_0.4.0   ggplot2_3.3.3  dplyr_1.0.6    gridExtra_2.3  nvimcom_0.9-28 colorout_1.2-0

#   loaded via a namespace (and not attached):
#    [1] zip_1.0.0         Rcpp_1.0.7        cellranger_1.1.0  pillar_1.6.1      compiler_3.6.3    forcats_0.5.1
#    [7] tools_3.6.3       lifecycle_1.0.0   tibble_3.1.2      gtable_0.3.0      pkgconfig_2.0.3   rlang_0.4.11
#   [13] openxlsx_4.1.0    DBI_1.0.0         curl_4.3          haven_2.3.1       rio_0.5.10        stringr_1.4.0
#   [19] withr_2.4.2       hms_1.0.0         generics_0.1.0    vctrs_0.3.8       grid_3.6.3        tidyselect_1.1.1
#   [25] glue_1.4.2        data.table_1.14.0 R6_2.5.0          rstatix_0.6.0     fansi_0.5.0       readxl_1.3.1
#   [31] foreign_0.8-76    carData_3.0-1     purrr_0.3.4       tidyr_1.1.3       car_3.0-0         magrittr_2.0.1
#   [37] scales_1.1.1      backports_1.2.1   ellipsis_0.3.2    abind_1.4-5       assertthat_0.2.1  colorspace_1.3-2
#   [43] ggsignif_0.6.0    utf8_1.2.1        stringi_1.4.6     munsell_0.5.0     broom_0.7.3       crayon_1.4.1


code_dir <- getwd()
data_dir <- gsub('code$', 'data', code_dir)
figs_dir <- gsub('code$', 'figures', code_dir)

setwd(data_dir)
vdem <- readRDS('V-Dem-CY-Full+Others-v10.rds')
ert <- read.csv('eps.csv') # episodes with V10 and ERT 2.0
setwd(figs_dir)

##### Function to grab country information
items_libaut_cf <-
  function(country = c(), years = c(1900, 2020)) 
  {
  eps <- ert
  vdem <- vdem
  subvdem <- vdem[,c("country_id", "country_name", "year", "e_chga_demo", "e_boix_regime")]
  eps <- merge(eps, subvdem, by=c("country_name", "year"))
  
  if(length(country) > 0) {
    eps_year <- eps %>%
      group_by(dem_ep_id) %>%
      mutate(dem_ep_outcome_all = max(dem_ep_outcome, na.rm=T)) %>%
      filter(country_name == country, between(year, min(years), max(years))) %>%
      filter(dem_ep_outcome != 5) %>%
      select(country_name, country_text_id, 
             year, v2x_polyarchy, 
             dem_ep_outcome, dem_ep_id,
             dem_ep_outcome_all, e_boix_regime, e_chga_demo) %>%
      mutate(episode_outcome = ifelse(dem_ep_outcome_all == 1, "Democratic Transition", NA),
             episode_outcome = ifelse(dem_ep_outcome_all == 2, "Preempted", episode_outcome),
             episode_outcome = ifelse(dem_ep_outcome_all == 3, "Stabilized", episode_outcome),
             episode_outcome = ifelse(dem_ep_outcome_all == 4, "Reverted", episode_outcome),
             episode_outcome = ifelse(dem_ep_outcome_all == 6, "Censored", episode_outcome)) 
    
    cf <- eps %>%
      filter(country_name == country, between(year, min(years), max(years))) %>%
      #filter(dem_ep_outcome != 0) %>%
      #group_by(dem_ep_id) %>%
      mutate(Lboix=lag(e_boix_regime), Lchga=lag(e_chga_demo))
      BMR<-cf[which(cf$Lboix==0 & cf$e_boix_regime==1),]$year
      CGV<-cf[which(cf$Lchga==0 & cf$e_chga_demo==1),]$year      

    # add EDI
    polyarchy <- eps %>%
      filter(country_name == country, between(year, min(years), max(years))) %>%
      ungroup() %>%
      select(year, v2x_polyarchy)
    
    # add Polity
    polity <- vdem %>%
      filter(country_name == country, between(year, min(years), max(years))) %>%
      ungroup() %>%
      select(year, e_polity2)
    
    eps_year<<-eps_year
    years<<-years
    cf<<-cf
    polity<<-polity
    polyarchy<<-polyarchy
    BMR<<-BMR
    CGV<<-CGV
  }
}

##### Figure 4

countries<-c("Ghana", "Burma/Myanmar", "El Salvador", "South Korea")

# plot countries individually
items_libaut_cf(countries[1])
BMRg<-BMR
CGVg<-CGV
g <-   ggplot2::ggplot() +
  geom_line(data = eps_year, aes(group = dem_ep_id, color = episode_outcome, x = year, y = v2x_polyarchy), size = 1) +
  geom_line(data = polyarchy, aes(x = year, y = v2x_polyarchy), alpha = 0.3) +
  scale_color_colorblind(limits = c("Democratic Transition", "Preempted", "Stabilized", "Reverted", "Censored"),
                         name = "",
                         labels = c("Democratic Transition", "Preempted", "Stabilized", "Reverted", "Censored")) +
  scale_x_continuous(breaks = seq(round(min(years) / 10) * 10, round(max(years) / 10) * 10, 20)) +
  xlab("") +  ylab("") + ylim(0,1) +
  geom_vline(aes(xintercept = BMRg), linetype = "solid", alpha = 0.2, size = 1) +
  geom_vline(aes(xintercept = CGVg), linetype = "dotted", alpha = 1, size = .75) +
  scale_linetype_manual(name = "", values = c(BMR = "BMR", CGV = "CGV"))+
  theme_classic() +
  theme(axis.text=element_text(size=14), axis.title=element_text(size=12), plot.title = element_text(size=16), legend.text = element_text(size = 14)) +
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) +
  theme(plot.margin = unit(c(5.5,5.5,5.5,5.5), "pt")) +
  ggtitle(sprintf("%s", countries[1])) +
  theme(legend.title = element_text(size = 15), legend.position="bottom")

items_libaut_cf(countries[2])
BMRb<-BMR
CGVb<-CGV
b <-   ggplot2::ggplot() +
  geom_line(data = eps_year, aes(group = dem_ep_id, color = episode_outcome, x = year, y = v2x_polyarchy), size = 1) +
  geom_line(data = polyarchy, aes(x = year, y = v2x_polyarchy), alpha = 0.3) +
  scale_color_colorblind(limits = c("Democratic Transition", "Preempted", "Stabilized", "Reverted", "Censored"),
                         name = "",
                         labels = c("Democratic Transition", "Preempted", "Stabilized", "Reverted", "Censored")) +
  scale_x_continuous(breaks = seq(round(min(years) / 10) * 10, round(max(years) / 10) * 10, 20)) +
  xlab("") +  ylab("") + ylim(0,1) +
  geom_vline(aes(xintercept = BMRb), linetype = "solid", alpha = 0.2, size = 1) +
  geom_vline(aes(xintercept = CGVb), linetype = "dotted", alpha = 1, size = .75) +
  scale_linetype_manual(name = "", values = c(BMR = "BMR", CGV = "CGV"))+
  theme_classic() +
  theme(axis.text=element_text(size=14), axis.title=element_text(size=12), plot.title = element_text(size=16), legend.text = element_text(size = 14)) +
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
  theme(plot.margin = unit(c(5.5,60,5.5,5.5), "pt")) +
  ggtitle(sprintf("%s", countries[2]))

items_libaut_cf(countries[3])
BMRe<-BMR
CGVe<-CGV
e <-   ggplot2::ggplot() +
  geom_line(data = eps_year, aes(group = dem_ep_id, color = episode_outcome, x = year, y = v2x_polyarchy), size = 1) +
  geom_line(data = polyarchy, aes(x = year, y = v2x_polyarchy), alpha = 0.3) +
  scale_color_colorblind(limits = c("Democratic Transition", "Preempted", "Stabilized", "Reverted", "Censored"),
                         name = "",
                         labels = c("Democratic Transition", "Preempted", "Stabilized", "Reverted", "Censored")) +
  scale_x_continuous(breaks = seq(round(min(years) / 10) * 10, round(max(years) / 10) * 10, 20)) +
  xlab("") +  ylab("") + ylim(0,1) +
  geom_vline(aes(xintercept = BMRe), linetype = "solid", alpha = 0.2, size = 1) +
  geom_vline(aes(xintercept = CGVe), linetype = "dotted", alpha = 1, size = .75) +
  scale_linetype_manual(name = "", values = c(BMR = "BMR", CGV = "CGV"))+
  theme_classic() +
  theme(axis.text=element_text(size=14), axis.title=element_text(size=12), plot.title = element_text(size=16), legend.text = element_text(size = 14)) +
  theme(plot.margin = unit(c(5.5,5.5,5.5,5.5), "pt")) +
  ggtitle(sprintf("%s", countries[3]))

items_libaut_cf(countries[4])
BMRs<-BMR
CGVs<-CGV
s <-   ggplot2::ggplot() +
  geom_line(data = eps_year, aes(group = dem_ep_id, color = episode_outcome, x = year, y = v2x_polyarchy), size = 1) +
  geom_line(data = polyarchy, aes(x = year, y = v2x_polyarchy), alpha = 0.3) +
  scale_color_colorblind(limits = c("Democratic Transition", "Preempted", "Stabilized", "Reverted", "Censored"),
                         name = "",
                         labels = c("Democratic Transition", "Preempted", "Stabilized", "Reverted", "Censored")) +
  scale_x_continuous(breaks = seq(round(min(years) / 10) * 10, round(max(years) / 10) * 10, 20)) +
  xlab("") +  ylab("") + ylim(0,1) +
  geom_vline(aes(xintercept = BMRs), linetype = "solid", alpha = 0.2, size = 1) +
  geom_vline(aes(xintercept = CGVs), linetype = "dotted", alpha = 1, size = .75) +
  scale_linetype_manual(name = "", values = c(BMR = "BMR", CGV = "CGV"))+
  theme_classic() +
  theme(axis.text=element_text(size=14), axis.title=element_text(size=12), plot.title = element_text(size=16), legend.text = element_text(size = 14)) +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
  theme(plot.margin = unit(c(5.5,60,5.5,5.5), "pt")) +
  ggtitle(sprintf("%s", countries[4]))

# Combining plots together
get_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}
g_legend<- get_legend(g)

fig4a_new <- grid.arrange(arrangeGrob(g + theme(legend.position="none"), 
                                      b + theme(legend.position="none"),
                                      nrow=1, ncol=2))
fig4b_new <- grid.arrange(arrangeGrob(e + theme(legend.position="none"), 
                                      s + theme(legend.position="none"),
                                      nrow=1, ncol=2))
fig4b_new <- annotate_figure(fig4b_new, bottom = text_grob("Year", size = 16))

# Now finally get fig4
fig4_new <- grid.arrange(arrangeGrob(fig4a_new, fig4b_new, nrow=2, heights=c(8, 10)), 
                        g_legend, nrow=2, heights=c(10, 1))
fig4_new <- annotate_figure(fig4_new,
                            left = text_grob("Electoral Democracy Index", rot = 90, size = 16))
fig4_new <- annotate_figure(fig4_new,
                            bottom = text_grob("Grey solid line: BMR     Black dotted line: CGV",
                                               size = 14,face = "plain"))


pdf("Figure_4_corrected.pdf", width=10, height=6)
#windowsFonts(A = windowsFont("Times New Roman"))
fig4_new
dev.off()

#   SCRIPT END
